package security.service.impl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import security.pojo.TPermissionEntity;
import security.pojo.TRolePermissionEntity;
import security.pojo.TUserEntity;
import security.pojo.TUserRoleEntity;
import security.repository.*;
import security.service.UserService;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author cyt
 * @create 2020-07-17 15:43
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private RolePremissionRepository rolePremissionRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private UserRoleRepository userRoleRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private PremissionRepository premissionRepository;

    @Override
    public TUserEntity getUserByUsername(String username) {
        TUserEntity t = userRepository.findByUsername(username);
        return t;
    }

    @Override
    public List<String> findPermissionsByUserId(String uid) {
        // UID 得到 角色
        TUserRoleEntity list = userRoleRepository.findByUserId(uid);

        log.info("role id => " + list.toString());
        //  角色 得到 权限
        ArrayList<TRolePermissionEntity> premissonList = rolePremissionRepository.findByRoleId(list.getRoleId());
        log.info("permission is  => " + premissonList.toString());

        ArrayList<String> arrayList = new ArrayList<>();
        for (TRolePermissionEntity entity : premissonList) {
            String id = entity.getPermissionId();
            log.info("permission id   => " + id);
            Long valueOf = Long.valueOf(id);
            Optional<TPermissionEntity> repository = premissionRepository.findById(valueOf);
            arrayList.add(repository.get().getCode());
        }
        return arrayList;
    }
}
